import { IApiItem, IImportData } from '@/utils/interfaces'
import { jsonSchemaToMock } from '../jsonSchemaToMock'

// yapi项转换成api项
export const yapiItemsToApiItems = async (
    items: any[],
    importData: IImportData,
) => {
    // 列表
    const result: IApiItem[] = []
    items.forEach((item) => {
        const { path, method, title, res_body } = item
        // 标题
        const label = title || path?.split('/').pop() || ''
        // api项
        const apiItem: IApiItem = {
            id: randomStr(),
            label,
            type: 'api',
            method,
            url: path,
            importData: {
                ...importData,
                yapiItem: item,
            },
        }

        if (res_body) {
            let schema = res_body
            try {
                schema = JSON.parse(res_body)
            } catch {}
            const mock =
                typeof schema === 'string' ? schema : jsonSchemaToMock(schema)
            apiItem.handlers = {
                resBody: {
                    enabled: true,
                    mockRule: JSON.stringify(mock, null, 2),
                },
            }
        }
        result.push(apiItem)
    })

    return result
}
